<template>
  <div class="app-container">
    <div class="main-card">
      <div class="card-header">
        <div class="header-title" style="position:relative;padding-left: 100px;"><img src="@/assets/images/top-logo.png"
            style="height:90px;position:absolute;top:-30px;left:20px;" alt="">
          <div>AI+政企服务助手|办事服务智能问答 · 联动大屏</div>
        </div>
      </div>
      <div class="card-content">
        <div v-if="msg" style="padding:20px;width: 100%;max-height: 100%;overflow-y: auto;">
          <div class="block" v-for="item in resDocs" v-if="item.type == 'image'" style="border-bottom:2px dashed #eaeaea;">

            <el-image v-if="!item.isArray" :style="'width:'+item.width+';margin:0 auto;max-width:80%;'" class="block" :src="item.url"
              :preview-src-list="imgList">
            </el-image>
            <el-image v-else v-for="url in item.url" :style="'width:'+item.width+';max-width:80%;'"
              :src="url" :preview-src-list="imgList">{{ item.width }}
            </el-image>
            <div class="demonstration txtc pt10 pb30" style="color:#777;">{{ item.title }}</div>
          </div>
          <div v-html="upContent(msg)">


          </div>
        </div>
      </div>
    </div>

    <el-dialog :title="videoTitle" :visible.sync="videoOpen" width="70%" center @close="closeVideo">
      <div>
        <video ref="videoPlayer" :src="videoUrl" :muted="isMuted" autoplay playsinline
          style="width: 100%;object-fit: cover;border:2px solid rgba(0, 0, 0, 0.5);max-height:80vh;"
          @enterpictureinpicture="videoOpen = !videoOpen" @leavepictureinpicture="videoOpen = !videoOpen" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" round plain type="primary" @click="togglePiP">切换画中画</el-button>
        <el-button size="small" round plain @click="toggleMute">{{ isMuted ? '开启声音' : '关闭声音' }}</el-button>
        <el-button size="small" round plain type="success" @click="play">重新播放</el-button>
        <!-- <el-button @click="closeVideo">关闭</el-button> -->
      </span>
    </el-dialog>




  </div>
</template>

<script>
import { getIpConfig, getIpConfigByBindingIp } from "@/api/wenda/ipConfig";
import { getJsonConfig } from "@/api/wenda/jsonConfig";
import { getConfig } from "@/api/wenda/homeConfig";
import langC from '@/api/wenda/langChain.js';
import markdown from '@/utils/wenda/markdown.js'; // 引入定义样式后的markdown

export default {
  name: "links",
  data() {
    return {
      uuid: null,
      ques: null,
      isEnd: true,
      timeout: 5 * 1000,
      setTime:null,
      lastTime: null,
      nowTime: null,
      msg: null,
      jsonId: null,
      agentId: null,
      homeConfig: null,

      resDocs: null,
      imgList: [],
      videoUrl: null,
      videoTitle: null,
      videoOpen: false,
      isMuted: true, // 是否静音
    };
  },
  created() {
    this.initLang()
  },
  methods: {
    closeVideo() {
      const video = this.$refs.videoPlayer;
      if (video) {
        video.pause(); // 暂停视频
        video.currentTime = 0; // 重置播放位置
        console.log('视频已停止');
      }
      this.isMuted = true
      this.videoOpen = false
    },
    toggleMute() {
      this.isMuted = !this.isMuted; // 切换静音状态
      console.log(this.isMuted ? '已关闭声音' : '已开启声音');
    },
    async togglePiP() {
      const video = this.$refs.videoPlayer;
      if (document.pictureInPictureElement === video) {
        await document.exitPictureInPicture();
      } else {
        await video.requestPictureInPicture();
      }
    },
    play() {
      this.videoOpen = true
      this.$nextTick(() => {
        const video = this.$refs.videoPlayer;
        if (video) {
          video.currentTime = 0;
          video.play().catch(error => {
            console.error('自动播放失败:', error);
          });
        }
      });
    },
    init() {
      if(this.setTime) clearTimeout(this.setTime)
        // 定时执行
        this.setTime = setTimeout(() => {
          this.nowTime = new Date(); // 获取当前时间
          const now = this.nowTime;

          if (this.lastTime) {
            const diff = now - this.lastTime; // 计算时间差（毫秒）
            console.log(`与上次执行时间差: ${diff}ms；当前时间: ${this.formatDate(this.nowTime)}；上次时间: ${this.formatDate(this.lastTime)}；`);
          } else {
            console.log("第一次执行");
          }
          this.lastTime = now; // 保存当前时间为下次对比的基准 
          this.init()
        }, this.timeout);

      getJsonConfig().then(res => {
        // console.log("获取json信息",res, res.data)
        const data = res.data
        // console.log("获取json信息", data.uuid, this.uuid)
        if (res.code == 200 && data.uuid == this.uuid) {
          // 数据不正确，旧数据重新生成
          if (!data.createTime || !data.json.length) {
            // console.log("error-re数据不正确，旧数据重新生成")
            return false
          }
          if (data.id <= this.jsonId) {
            // console.log("jsonId已有，不重复添加")
            return false
          }
          const jsonTime = data.createTime.replace(' ', 'T');
          const nowTime = data.nowDataTime.replace(' ', 'T');
          const createTime = new Date(jsonTime).getTime();
          const nowDataTime = new Date(nowTime).getTime();


          const diff = nowDataTime - createTime;
          // console.log("createTime",diff,nowDataTime,createTime)
          // console.log("createTime",data.createTime,createTime,now)
          // console.log("diff", Math.abs(diff), this.timeout)
          if (Math.abs(diff) < parseInt(this.timeout + 2000)) { // 去除定时器调用波动的干扰
            const msgArr = JSON.parse(data.json)
            console.log("data.json",msgArr)
            this.jsonId = JSON.parse(data.id)
            this.ques = msgArr[0].content
            this.agentId = msgArr[0].assistant_id
            this.submitQues();
          }
        }

      }).finally(() => {

      });
    },
    formatDate(date) {
      return `${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    },
    async initLang() {
      getIpConfigByBindingIp().then(res => {
        console.log("getIpConfigByBindingIp", res)
        if (res.data && res.data.uuid) {
          this.uuid = res.data.uuid
        } else {
          this.$modal.msgWarning("请在后台绑定当前设备")
          return false
        }
        this.init()
      })
    },
    async submitQues() {
      this.isEnd = false
      if (!this.ques) {
        return false
      }


      // 提交问题后，带入线程,无线程时,重新生成
      const text = this.ques.replace('并且以中文回复，回复内容中不包含附件参考信息', '');

      this.thread = await langC.threadCreate({
        "thread_id": "",
        "metadata": { graph_id: "agent", ques: "link " + text, uuid: "link " + this.uuid, type: "links" },
        "if_exists": "raise",
      })
      this.chatUserCLickStream()
    },
    // stream:true 开始
    // 异步流式--提交
    async chatUserCLickStream() {

      this.isThink = false // 调整传输数据状态
      this.isContent = true
      let messages = [{ type: "human", name: "user", content:this.ques}]
      console.warn("提问数据:",messages)
      let a = langC.runsStream(this.thread.thread_id, this.agentId, { input: { messages: messages }, streamMode: ["updates", "messages"] })
      for await (const chunk of a) {

        if (chunk.event == "updates") {
          if (chunk.data.retrieve && chunk.data.retrieve.retrieved_docs.length) {
            console.log("chunk.data.retrieve.retrieved_docs:", chunk.data.retrieve.retrieved_docs);
            const docs = chunk.data.retrieve.retrieved_docs
            for (let d = 0; d < docs.length; d++) {
              const str = docs[d].page_content
              if (str.indexOf('resStart:') >= 0) {
                // const arrayStr = resDocs
                const arrayStr = str.split('resStart:')[1]; // 分割字符串，取数组部分

                // 3. 解析为 JSON 对象
                console.log("resDocs", arrayStr)
                this.resDocs = JSON.parse(arrayStr.split("'").join('"'))
                console.log("resDocs", this.resDocs)
                if (this.resDocs.length) {
                  for (let i = 0; i < this.resDocs.length; i++) {
                    // console.log("this.resDocs[i]", this.resDocs[i],this.resDocs[i].type)
                    if (this.resDocs[i].type == "video") {
                      this.videoUrl = this.resDocs[i].url
                      this.videoTitle = this.resDocs[i].title
                      this.play()
                    } else if (this.resDocs[i].type == "image") {
                      if (this.resDocs[i].isArray) {
                        this.imgList.push(...this.resDocs[i].url)
                      } else {
                        this.imgList.push(this.resDocs[i].url)
                      }
                    }
                  }
                  // console.log("imgList",this.imgList)
                }
                break
              }
            }
          }

          this.isContent = true
          this.isThink = false
        } else if (chunk.event == "messages/partial") {
          this.msg = chunk.data[0].content

          if (chunk.data[0].response_metadata.done_reason == "stop" || chunk.data[0].response_metadata.finish_reason == "stop") {
            this.isEnd = true // 重置状态
            this.isUserEnd = true
            this.isContent = false
            this.isThink = false
          }

        }
        if (chunk.event == "values") {
          const msgArr = chunk.data.messages
          // if(msgArr[msgArr.length-1].type === "ai" && msgArr[msgArr.length-1].content.length){
          //   this.isEnd = true
          //   this.msg = msgArr[msgArr.length-1].content
          // }
          if (msgArr[msgArr.length - 1].type === "ai" && msgArr[msgArr.length - 1].content.length) {
            const msg = msgArr[msgArr.length - 1]
            this.msg = msg // 更新最后一条消息
            this.isEnd = true // 重置状态
            this.isUserEnd = true
            this.isThink = false
            this.isContent = true
          }
        } else if (chunk.event == "messages/partial") {
          this.msg = chunk.data[0].content

        }
      }
    },
    upContent(text) {
      if (text) {
        return markdown.returnContent(text)
      }
    },
  },
};
</script>

<style scoped>
.app-container {
  display: flex;
  height: calc(100vh);
  padding: 55px;
  background: -webkit-linear-gradient(#C2DBFA, #DAE0FA, #F5F6FA);
  background: linear-gradient(#C2DBFA, #DAE0FA, #F5F6FA);
}

.main-card {
  box-sizing: border-box;
  width: 100%;
  background: #fff;
  border-radius: 15px;
  box-shadow: rgba(100, 100, 100, 0.1) 1px 2px 3px;
  position: relative;
}

.card-header {
  border-radius: 15px 15px 0 0;
  height: 100px;
  background: -webkit-linear-gradient(to right, #409eff, #B271B7, #409eff, #2E82FC, #1890FF, #409eff, #1890FF, #409eff);
  background: linear-gradient(to right, #409eff, #B271B7, #409eff, #2E82FC, #1890FF, #409eff, #1890FF, #409eff);
}

.icon-shouye {
  position: absolute;
  top: 25px;
  right: 25px;
  font-size: 25px;
  color: #fff;
  z-index: 5;
}

.header-img {
  height: 100%;
}

.header-img img {
  height: 120%;
}

.header-title {
  height: 100%;
  line-height: 80px;
  padding-left: 30px;
  color: #fff;
  font-size: 23px;
  letter-spacing: 8px;
}

.header-title>div {
  height: 100%;
  overflow: hidden;
}

.card-content {
  margin-top: -20px;
  background: #fff;
  height: calc(100% - 80px);
  display: flex;
  overflow: hidden;
  border-radius: 15px;

}

@media (max-width: 768px) {}
</style>
